package com.unionftech.content_login.util

import android.text.TextUtils
import com.google.gson.Gson
import com.unionftech.baselibrary.network.RetrofitClient
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.common.GlobalInfoManager
import com.unionftech.common.utils.SpUtils
import com.unionftech.content_login.api.AuthRefreshApi
import com.unionftech.content_login.bean.LoginTokenInfo

class TokenManager private constructor() {

    private val mGson by lazy { Gson() }
    private lateinit var mAuthRefreshApi: AuthRefreshApi

    companion object {
        /**
         * 用户登录token存储key
         */
        const val KEY_TOKEN = "user_token"
        const val KEY_AUTH = "Authorization"

        @Volatile
        private var instance: TokenManager? = null

        @JvmStatic
        fun getInstance() = instance ?: synchronized(TokenManager::class.java) {
            instance ?: TokenManager().also {
                instance = it
            }
        }
    }


    /**
     * 返回用户是否登录
     */
    fun isLogin(): Boolean {
        val token = getAccessToken()
        return !TextUtils.isEmpty(token)
    }

    /**
     * 获取网络请求需要传递的token在Header中的key
     */
    fun getHeaderTokenKey(): String {
        return KEY_AUTH
    }

    /**
     * 判断接口的返回code 是否token过期
     */
    fun isTokenExpired(responseBodyString: String): Boolean {
        try {
            val responseResult = mGson.fromJson(responseBodyString, ResponseResult::class.java)
            if (responseResult.code == ResponseResult.LOGIN_EXPIRED) {
                return true
            }
            return false
        } catch (e: Exception) {
            return false
        }
    }

    /**
     * 返回当前过期的token并将其清除
     */
    fun clearExpiredToken(): String {
        //目前的系统是刷新token的有效期，不清除
        return getAccessToken()
    }


    /**
     * 向服务器请求最新的token
     */
    fun asyncRefreshToken(token: String): Any? {
        if (!::mAuthRefreshApi.isInitialized) {
            mAuthRefreshApi =
                RetrofitClient.getInstance().createNoTokenInterceptor(AuthRefreshApi::class.java)
        }
        val responseResult = mAuthRefreshApi.refreshToken(token).execute().body()
        if (responseResult?.code != ResponseResult.SUCCESS_CODE) {
            if (responseResult?.code == ResponseResult.LOGIN_EXPIRED) {
                return ResponseResult.LOGIN_EXPIRED
            }
            return null
        }
        return SpUtils.getInstance().getParcelable(
            KEY_TOKEN, LoginTokenInfo::class.java
        ) as? LoginTokenInfo
    }

    /**
     * 保存 token对象
     */
    fun saveToken(tokenInfo: LoginTokenInfo) {
        GlobalInfoManager.getInstance().updateToken(tokenInfo.access_token)
        SpUtils.getInstance().put(KEY_TOKEN, tokenInfo)
    }

    /**
     * 获取当前的可用token
     */
    fun getAccessToken(): String {
        val tokenInfo = SpUtils.getInstance().getParcelable(
            KEY_TOKEN, LoginTokenInfo::class.java
        ) as? LoginTokenInfo
        return tokenInfo?.access_token ?: ""
    }

    /**
     * 重新登录的时候需要清除token
     */
    fun clearTokenInfo() {
        GlobalInfoManager.getInstance().updateToken("")
        SpUtils.getInstance().remove(KEY_TOKEN)
    }
}